/* Created on 2006-9-19 */
/**
 *
 */
package com.xbang.core.web.loader;

import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author dev.zhang
 */
public class ServletContextLoaderImpl implements ServletContextLoader, InitializingBean {

	private static final Log logger = LogFactory.getLog(ServletContextLoaderImpl.class);

	private List<ServletContextLoader> servletContextLoaders;

	private String loaders;

	/**
	 * @param servletContextLoaders
	 *            The servletContextLoaders to set.
	 */
	public void setServletContextLoaders(List<ServletContextLoader> servletContextLoaders) {
		this.servletContextLoaders = servletContextLoaders;
		this.loaders = servletContextLoaders.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		for (int i = 0; i < servletContextLoaders.size(); i++) {
			// check every servletContextLoader and set to loaders
			Object loader = servletContextLoaders.get(i);
			if (!(loader instanceof ServletContextLoader)) {
				throw new IllegalArgumentException("Unsupported ServletContextLoader:" + loader.getClass());
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.adt.surecenter.loader.ServletContextLoader#initServletContext(javax.servlet.ServletContext)
	 */
	public void initServletContext(ServletContext servletContext) {
		if (logger.isDebugEnabled()) {
			logger.debug("Init Servlet Context:" + loaders);
		}
		for (int i = 0; i < servletContextLoaders.size(); i++) {
			ServletContextLoader loader = servletContextLoaders.get(i);
			loader.initServletContext(servletContext);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.adt.surecenter.loader.ServletContextLoader#closeServletContext(javax.servlet.ServletContext)
	 */
	public void closeServletContext(ServletContext servletContext) {
		if (logger.isDebugEnabled()) {
			logger.debug("Init Servlet Context." + loaders);
		}
		for (int i = 0; i < servletContextLoaders.size(); i++) {
			ServletContextLoader loader = servletContextLoaders.get(i);
			loader.closeServletContext(servletContext);
		}
	}

}
